package com.example.mediaservice;

import android.support.v4.media.MediaDescriptionCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.media.MediaBrowserServiceCompat;
import androidx.media.session.MediaButtonReceiver;

import java.util.ArrayList;
import java.util.List;

public class MediaService extends MediaBrowserServiceCompat {
    private static final String TAG = "MediaService";// 日志标签
    private MediaSessionCompat mediaSession; // 媒体会话对象
    private boolean isPlaying = false; // 播放状态标志
    private static final String CHANNEL_ID = "media_channel"; // 通知通道ID
    private static final int NOTIFICATION_ID = 1; // 通知ID
    private static final String MEDIA_ROOT_ID = "media_root_id";// 媒体根ID
    // 添加媒体列表和当前播放索引
    private List<MediaItem> mediaList; // 媒体列表
    private int currentMediaIndex = 0; // 当前播放索引
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "MediaService onCreate");
        // 初始化媒体列表（示例数据）
        initMediaList();
        // 创建媒体会话
        mediaSession = new MediaSessionCompat(this, "MediaService");
        // 设置初始媒体元数据（第一首歌曲信息）
        updateMediaMetadata(currentMediaIndex);
        // 设置播放状态
        updatePlaybackState();

        // 设置会话令牌
        setSessionToken(mediaSession.getSessionToken());

        // 设置回调处理播放控制
        mediaSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                isPlaying = true;
                updatePlaybackState();
                startForeground(NOTIFICATION_ID, createNotification());
            }

            @Override
            public void onPause() {
                isPlaying = false;
                updatePlaybackState();
            }

            @Override
            public void onSkipToNext() {
                skipToNext();
            }

            @Override
            public void onSkipToPrevious() {
                skipToPrevious();
            }
            @Override
            public void onSeekTo(long pos) {
                SeekTo(pos);
            }
        });

        // 创建通知通道
        createNotificationChannel();

        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());
    }
    /**
     * 初始化媒体列表（示例数据）
     */
    private void initMediaList() {
        mediaList = new ArrayList<>();
        mediaList.add(new MediaItem("1", "稻香", "周杰伦", 240000)); // 240秒
        mediaList.add(new MediaItem("2", "青花瓷", "周杰伦", 218000)); // 218秒
        mediaList.add(new MediaItem("3", "夜曲", "周杰伦", 225000)); // 225秒
        mediaList.add(new MediaItem("4", "告白气球", "周杰伦", 219000)); // 219秒
        mediaList.add(new MediaItem("5", "简单爱", "周杰伦", 263000)); // 263秒
    }
    /**
     * 更新媒体元数据
     * @param index 媒体索引
     */
    private void updateMediaMetadata(int index) {
        if (mediaList == null || index < 0 || index >= mediaList.size()) {
            return;
        }

        MediaItem item = mediaList.get(index);
        MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
                .putString(MediaMetadataCompat.METADATA_KEY_TITLE, item.title)
                .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, item.artist)
                .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, item.duration)
                .build();
        mediaSession.setMetadata(metadata);
    }
    /**
     * 跳到下一首
     */
    private void skipToNext() {
        Log.d(TAG, "skipToNext called");

        // 检查媒体列表是否为空
        if (mediaList == null || mediaList.isEmpty()) {
            Log.w(TAG, "Media list is empty");
            return;
        }

        // 计算下一首的索引（循环播放）
        currentMediaIndex = (currentMediaIndex + 1) % mediaList.size();

        // 更新媒体元数据
        updateMediaMetadata(currentMediaIndex);

        // 更新播放状态
        updatePlaybackState();

        // 更新通知
        updateNotification();

        Log.d(TAG, "Skipped to next track: " + currentMediaIndex);
    }

    /**
     * 跳到上一首
     */
    private void skipToPrevious() {
        Log.d(TAG, "skipToPrevious called");

        // 检查媒体列表是否为空
        if (mediaList == null || mediaList.isEmpty()) {
            Log.w(TAG, "Media list is empty");
            return;
        }

        // 计算上一首的索引（循环播放）
        currentMediaIndex = (currentMediaIndex - 1 + mediaList.size()) % mediaList.size();

        // 更新媒体元数据
        updateMediaMetadata(currentMediaIndex);

        // 更新播放状态
        updatePlaybackState();

        // 更新通知
        updateNotification();

        Log.d(TAG, "Skipped to previous track: " + currentMediaIndex);
    }
    public void SeekTo(long pos) {
        Log.d(TAG, "onSeekTo called with position: " + pos);

        // 更新播放位置
        // 注意：由于您当前使用的是示例数据，没有实际的MediaPlayer，所以这里主要是更新状态

        // 构建新的播放状态，包含指定的位置
        int state = isPlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder()
                .setState(state, pos, 1.0f)  // 设置状态、位置和播放速度
                .setActions(PlaybackStateCompat.ACTION_PLAY |
                        PlaybackStateCompat.ACTION_PAUSE |
                        PlaybackStateCompat.ACTION_PLAY_PAUSE |
                        PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
                        PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                        PlaybackStateCompat.ACTION_SEEK_TO)  // 确保包含SEEK_TO动作
                .build();

        // 更新媒体会话的播放状态
        mediaSession.setPlaybackState(playbackState);

        Log.d(TAG, "Playback state updated with position: " + pos);
    }

    /**
     * 更新媒体播放状态
     * 该方法根据当前播放状态创建PlaybackStateCompat对象，并将其设置到mediaSession中。
     * 主要用于通知系统当前媒体的播放状态（播放中或暂停），以及支持的播放控制操作。
     */
    private void updatePlaybackState() {
        // 根据当前播放状态确定要设置的播放状态值
        int state = isPlaying ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        long position = 0;
        // 构建播放状态对象，包含状态、位置、播放速度和支持的操作
        PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder()
                .setState(state, position, 1.0f)
                .setActions(PlaybackStateCompat.ACTION_PLAY |
                        PlaybackStateCompat.ACTION_PAUSE |
                        PlaybackStateCompat.ACTION_PLAY_PAUSE |
                        PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
                        PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS|
                        PlaybackStateCompat.ACTION_SEEK_TO)
                .build();
        // 将构建好的播放状态设置到媒体会话中
        mediaSession.setPlaybackState(playbackState);
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "媒体播放",
                    NotificationManager.IMPORTANCE_LOW
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
    /**
     * 创建媒体播放通知 在 Android 系统的通知栏中显示媒体播放控制界面
     */
    private Notification createNotification() {
        // 创建通知点击意图
        Intent intent = new Intent(this, MainActivity.class);
        //PendingIntent 是一个延迟执行的 Intent，通常用于由其他组件（如通知或其他系统服务）触发的场景
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );

        // 获取当前媒体信息
        MediaMetadataCompat metadata = mediaSession.getController().getMetadata();
        String title = "未知歌曲";
        String artist = "未知艺术家";

        if (metadata != null) {
            title = metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
            artist = metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
        }

        // 创建通知构建器实例，用于构建媒体播放通知
        // 设置通知渠道ID为CHANNEL_ID
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(artist)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                        .setMediaSession(mediaSession.getSessionToken())
                        .setShowActionsInCompactView(0, 1, 2))
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

        // 添加上一首按钮
        builder.addAction(new NotificationCompat.Action(
                android.R.drawable.ic_media_previous, "上一首",
                MediaButtonReceiver.buildMediaButtonPendingIntent(
                        this, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)));

        // 添加播放/暂停按钮
        if (isPlaying) {
            builder.addAction(new NotificationCompat.Action(
                    android.R.drawable.ic_media_pause, "暂停",
                    MediaButtonReceiver.buildMediaButtonPendingIntent(
                            this, PlaybackStateCompat.ACTION_PAUSE)));
        } else {
            builder.addAction(new NotificationCompat.Action(
                    android.R.drawable.ic_media_play, "播放",
                    MediaButtonReceiver.buildMediaButtonPendingIntent(
                            this, PlaybackStateCompat.ACTION_PLAY)));
        }

        // 添加下一首按钮
        builder.addAction(new NotificationCompat.Action(
                android.R.drawable.ic_media_next, "下一首",
                MediaButtonReceiver.buildMediaButtonPendingIntent(
                        this, PlaybackStateCompat.ACTION_SKIP_TO_NEXT)));

        return builder.build();
    }


    /**
     * 更新通知
     */
    private void updateNotification() {
        Notification notification = createNotification();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 处理媒体按钮事件，将意图转发给媒体会话进行处理
        MediaButtonReceiver.handleIntent(mediaSession, intent);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mediaSession.release();
        stopForeground(true);
        super.onDestroy();
    }
    /**
     * 客户端首次连接时调用，返回 BrowserRoot 对象定义媒体内容根节点。
     */
    @Nullable
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
        Log.d(TAG, "Client connecting: " + clientPackageName);
        // 允许所有客户端连接
        return new BrowserRoot(MEDIA_ROOT_ID, null);
    }


    @Override
    public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
        Log.d(TAG, "onLoadChildren called with parentId: " + parentId);

        // 返回媒体列表
        List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
        if (mediaList != null) {
            for (MediaItem item : mediaList) {
                MediaBrowserCompat.MediaItem mediaItem = new MediaBrowserCompat.MediaItem(
                        new MediaDescriptionCompat.Builder()
                                .setMediaId(item.id)
                                .setTitle(item.title)
                                .setSubtitle(item.artist)
                                .build(),
                        MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
                );
                mediaItems.add(mediaItem);
            }
        }
        result.sendResult(mediaItems);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent); // 使用父类的 onBind
    }
    /**
     * 媒体项内部类
     */
    private static class MediaItem {
        final String id;
        final String title;
        final String artist;
        final long duration; // 毫秒

        MediaItem(String id, String title, String artist, long duration) {
            this.id = id;
            this.title = title;
            this.artist = artist;
            this.duration = duration;
        }
    }
}
